import style from './index.module.less'
import { Popup, Form, Button, Toast } from 'antd-mobile'
import { AddOutline } from 'antd-mobile-icons'
import PageComponent from '@components/pageComponent'
import { useEffect, useMemo, useState } from 'react'
import Selector from '@components/selector'
import { getCaseDetailRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import Dictionary from '@src/assets/js/dictionary'
import FilePicker from '@components/filePicker'
import MultiSelector from '@components/multiSelector'
import { requestFiles } from '@src/assets/js/request'
import { setProgress, setProgressVisible } from '@src/redux/reducers/common'
import { useAppDispatch } from '@src/redux/hook'

const { Item, useForm } = Form

async function initCaseDetail (id, setData, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseDetailRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    setData(d)
  }
}

function formatSumbitData (d, apply) {
  d.party = d.party instanceof Array && d.party.length > 0 ? d.party.join(',') : null
  d.scope = d.scope instanceof Array && d.scope.length > 0 ? d.scope.join(',') : null
  d.scope_type = d.scope_type instanceof Array && d.scope_type.length > 0 ? d.scope_type.join(',') : null
  if (apply) {
    d.type = '申请人'
  } else {
    d.type = '被申请人'
  }
}

async function submitHandle (d, apply, list, current, onChange, setVisible, setCurrent, dispatch) {
  if (list.find(li => li.partyid === d.partyid)) {
    Toast.show({ content: '已存在该代理对象', icon: 'fail' })
    return undefined
  }
  formatSumbitData(d, apply)
  if (d.upload && d.upload.length > 0) {
    dispatch(setProgressVisible(true))
    const [e, r] = await awaitWrap(requestFiles(d.upload, (v) => { dispatch(setProgress(v)) }))
    dispatch(setProgressVisible(false))
    if (e !== null) {
      return undefined
    }
    if (e === null && r !== null) {
      d.fileid = r.map(li => li.id).join(',')
      d.file = r
    }
  }
  delete d.upload
  if (current) {
    const i = list.indexOf(current)
    const l = [...list]
    l.splice(i, 1, d)
    onChange(l)
  } else {
    const l = [...list, d]
    onChange(l)
  }
  setVisible(false)
  setCurrent(null)
}

function Line ({ data, list, onClick }) {
  const name = useMemo(() => {
    const o = list.find(li => li.id === data.partyid)
    if (o) {
      return o.name
    }
    return ''
  }, [data, list])
  return <a className={style.item} onClick={onClick}>{name}</a>
}

function Main ({ value = [], onChange = () => {}, caseid, apply = false }) {
  const [formRef] = useForm()
  const dispatch = useAppDispatch()
  const [visible, setVisible] = useState(false)
  const [caseDetail, setCaseDetail] = useState(null)
  const [options1, setOptions1] = useState([])
  const [current, setCurrent] = useState(null)
  const [loading, setLoading] = useState(false)
  const partys = useMemo(() => {
    if (!caseDetail) {
      return []
    }
    if (apply) {
      return caseDetail.applicants || []
    }
    return caseDetail.respondents || []
  }, [caseDetail, apply])
  const partyNames = useMemo(() => {
    return partys.map(p => p.name)
  }, [partys])
  useEffect(() => {
    if (caseid) {
      initCaseDetail(caseid, setCaseDetail, setLoading)
    }
  }, [caseid])
  useEffect(() => {
    const d = new Dictionary()
    d.init('特殊代理权限')
      .then(() => {
        setOptions1(d.getList('特殊代理权限').map(li => li.title))
      })
  }, [])
  useEffect(() => {
    if (formRef && !visible) {
      formRef.resetFields()
    }
  }, [formRef, visible])
  useEffect(() => {
    if (formRef && visible && current) {
      formRef.setFieldsValue({
        type: apply ? '申请人' : '被申请人',
        party: typeof current.party === 'string' ? current.party.split(',') : [],
        scope: typeof current.scope === 'string' ? current.scope.split(',') : [],
        scope_type: typeof current.scope_type === 'string' ? current.scope_type.split(',') : [],
        upload: current.file || []
      })
    }
  }, [formRef, visible, current, apply])
  return (
    <div className={style.container}>
      <div className={style.list}>
        {
          !loading && value.map((li, i) => {
            return (
              <Line data={li} key={i} list={partys} onClick={() => { setCurrent(li); setVisible(true) }} />
            )
          })
        }
      </div>
      <button className={style.add} type='button' onClick={() => setVisible(true)}>
        <AddOutline />
        <span>添加</span>
      </button>
      <Popup position='right' bodyStyle={{ width: '100vw' }} forceRender mask={false} visible={visible} onClose={() => setVisible(false)}>
        <PageComponent title={'添加代理对象'} onBack={() => { setVisible(false); setCurrent(null) }}>
          <Form layout='horizontal' form={formRef} onFinish={(d) => {
            submitHandle(d, apply, value, current, onChange, setVisible, setCurrent, dispatch)
          }}>
            <Item name='type' noStyle><span /></Item>
            <Item name='partyid' noStyle><span /></Item>
            <Selector name='party' label='代理对象' rules={[{ required: true, message: '代理对象不能为空' }]} options={partyNames} formRef={formRef} onChange={v => {
              if (!v) {
                formRef.setFieldValue('partyid', '')
              } else {
                const o = partys.find(li => li.name === v)
                if (o) {
                  formRef.setFieldValue('partyid', o.id)
                }
              }
            }} />
            <Selector name='scope_type' label='代理类型' rules={[{ required: false, message: '代理类型不能为空' }]} options={['一般代理', '特殊代理']} formRef={formRef} />
            <Item shouldUpdate={(prev, cur) => prev.scope_type !== cur.scope_type} noStyle>
              {
                ({ getFieldValue }) => {
                  const t = getFieldValue('scope_type') || [null]
                  if (t[0] === '特殊代理') {
                    return (
                      <MultiSelector name='scope' label='代理权限' options={options1} formRef={formRef} />
                    )
                  }
                  return <span />
                }
              }
            </Item>
            <Item name='upload' label='代理附件' rules={[{ required: false, message: '代理附件不能为空' }]}>
              <FilePicker />
            </Item>
          </Form>
          <div className={style.btns}>
            <Button color='primary' block onClick={() => { formRef.submit() }}>提交</Button>
            {current && (
              <Button className={style.del} type='button' block onClick={() => {
                const i = value.indexOf(current)
                const l = [...value]
                l.splice(i, 1)
                onChange(l)
                setCurrent(null)
                setVisible(false)
              }}>删除</Button>
            )}
          </div>
        </PageComponent>
      </Popup>
    </div>
  )
}

export default Main
